package com.salon.client.widgets;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.salon.client.beans.WhereBean;
import com.salon.client.tabItems.MaterialTabItemPanel;

public class MaterialSearchDialog extends Dialog{
	
	MaterialTabItemPanel parentPanel = null;
	TextField<String> name = new TextField<String>();
	TextField<String> code = new TextField<String>();
	
	public MaterialSearchDialog(MaterialTabItemPanel parentPanel) {
		this.parentPanel = parentPanel;
		setHeading("Поиск материалов");
		setButtons(Dialog.OKCANCEL);
		FormLayout layout = new FormLayout();
	    layout.setLabelWidth(90);
	    layout.setDefaultWidth(200);
	    setLayout(layout);
	    
	    setIcon(IconHelper.createStyle("user"));
	    setModal(false);
	    setBodyBorder(true);
	    setBodyStyle("padding: 8px;background: none");
	    setWidth(400);
	    setResizable(false);
	    
		initTable();	
		show();
	}
	
	private void initTable() {
		name.setFieldLabel("Наименование");
		add(name);
		
		code.setFieldLabel("Код");
		add(code);
		
		Button ok = getButtonById(Dialog.OK);
		ok.setText("Искать");
		ok.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {			
				List<WhereBean> list = getWheres();
				hide();
				removeAllListeners();
				removeFromParent();
				parentPanel.search(list);
			}
			
		});
		
		Button cancel = getButtonById(Dialog.CANCEL);
		cancel.setText("Отмена");
		cancel.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {				
				hide();
				removeAllListeners();
				removeFromParent();
			}
			
		});
		
	}
	
	private List<WhereBean> getWheres() {
		List<WhereBean> list = new ArrayList<WhereBean>();
		if (name.getValue() != null && name.getValue().length() > 0) {
			list.add(new WhereBean("name",  "%" + name.getValue() + "%", WhereBean.Operator.LIKE));
		}
		
		if (code.getValue() != null && code.getValue().length() > 0) {
			list.add(new WhereBean("code",  "%" + code.getValue() + "%", WhereBean.Operator.LIKE));
		}
		
		return list;
	}
}